package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.vo.ForgetVo;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author Yoo19
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-07-15 09:05:44
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public R login(LoginInfoVo loginInfoVo) {
        TbUser user = tbUserMapper.selectOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, loginInfoVo.getUserMobile()).or().eq(TbUser::getUserEmail, loginInfoVo.getUserEmail()));
        if(user == null){
            return R.ERROR(500,"该用户不存在");
        }
        //加密
        String encrypt = MD5Utils.encrypt(loginInfoVo.getUserPass());
        System.out.println("加密后的密码为："+ encrypt);

        //判断密码是否正确
        if(!user.getUserPass().equals(encrypt)){
            return R.ERROR(500,"密码错误,请重新输入");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId()).compact();
        String redisKey = "token-" + user.getUserId();
        redisTemplate.opsForValue().set(redisKey,token,30, TimeUnit.MINUTES);

        user.setUserPass(null);
        user.setToken(token);
        return R.OK(user);
    }

    @Override
    public R register(TbUser tbUser) {
        TbUser user = tbUserMapper.selectOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, tbUser.getUserMobile()));
        if(user != null){
            return R.ERROR(500,"该用户已存在,请直接登陆");
        }
        //	为保证用户密码的隐私，后台存储需要使用encrypt进行密码加密
        String encrypt = MD5Utils.encrypt(tbUser.getUserPass());
        tbUser.setUserPass(encrypt);
        tbUserMapper.insert(tbUser);
        return R.OK();
    }

    @Override
    public R sendCode(String mobile) {
        //生成验证码并发送
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码为：" + code);
        String key = "code-" + mobile;
        redisTemplate.opsForValue().set(key,code,5,TimeUnit.MINUTES);
        return R.OK();
    }

    @Override
    public R forget(ForgetVo forgetVo) {
        //需要先校验是否存在此用户，若不存在则需要进行提示
        TbUser user = tbUserMapper.selectOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, forgetVo.getUserMobile()));
        if(user == null){
            return R.ERROR(500,"该用户不存在,请先注册");
        }
        //发送验证码并从缓存获取
        String key = "code-" + forgetVo.getUserMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        //若验证码错误并获取失败次数
        int failNum = 0;

        if(!forgetVo.getCode().equals(redisCode)){
            for (int i = 0; i <= failNum; i++) {
                failNum = failNum + 1;
                if(failNum == 3){
                    break;
                }
            }
        }

        //若输入错误3次，则需要让本次发送的验证码失效
        if(failNum >= 3){
            redisTemplate.delete(key);
        }
        //改密码需要使用encrypt进行密码加密
        String encrypt = MD5Utils.encrypt(forgetVo.getUserPass());
        System.out.println("加密后的密码为:" + encrypt);
        user.setUserPass(encrypt);
        tbUserMapper.updateById(user);
        return R.OK();
    }
}




